<?php
/*
 * @Author       : chaihao
 * @Date         : 2020-06-05 10:28:54
 * @FilePath     : /xunao/ai/Services/api/UserCardService.php
 */

namespace app\Services\api;

use app\commands\Helper;
use app\models\Ivtcode;
use app\models\PltfCard;
use app\models\PltfSendCard;
use app\models\Room;
use app\models\Seat;
use app\models\Seattimeline;
use app\models\User;
use app\models\UserAvter;
use app\models\UserLimit;
use app\Services\ApiService;
use Yii;
use yii\db\Exception;

class UserCardService extends ApiService
{
    /**
     * 返回该用户名片样式
     */
    public function getCardStyle($user_id)
    {
        if (isset($user_id) && !empty($user_id)) {
            $userCard =  PltfCard::find()->where(['userID' => $user_id])->orderBy(['id' => SORT_DESC])->asArray()->one();
            if (empty($userCard)) {
                return ['code' => -1, 'message' => '未找到信息'];
            }
            $content = $userCard['style'] . '/' . $userCard['Activity'];
            return ['code' => 200, 'data' => $content];
        }
        return ['code' => -1, 'message' => '参数错误'];
    }

    /**
     * 修改该用户名片样式为传参的style
     *
     * @param [type] $data
     * @return void
     */
    public function setCardStyle($data)
    {
        $info = [
            'style' => $data['style']
        ];
        try {
            Yii::$app->db->createCommand()->update(PltfCard::tableName(), $info, ['userID' => $data['user_id']])->execute();
            return ['code' => 200, 'message' => '操作成功'];
        } catch (Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }

    /**
     * 返回该用户隐私设置
     *
     * @param [type] $data
     * @return void
     */
    public function getLimit($data)
    {
        $result = UserLimit::find()->where(['userID' => $data['user_id']])->asArray()->one();
        if (empty($result)) {
            return  ['code' => -1, 'message' => '未查找到数据'];
        }
        $content = '';
        $content = $result['message'] . '/' . $result['card'];
        return  ['code' => 200, 'data' => $content];
    }

    /**
     * 修改该用户隐私设置
     *
     * @param [type] $data
     * @return void
     */
    public function setLimit($data)
    {
        $info = [];
        if (isset($data['message']) && in_array($data['message'], [0, 1])) {
            $info['message'] = (int) $data['message'];
        }
        if (isset($data['card']) && in_array($data['card'], [0, 1])) {
            $info['card'] = (int) $data['card'];
        }
        if (empty($info)) {
            return ['code' => -1, 'message' => '参数错误'];
        }
        try {
            Yii::$app->db->createCommand()->update(UserLimit::tableName(), $info, ['userID' => $data['user_id']])->execute();
            return ['code' => 200, 'message' => '操作成功'];
        } catch (Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }

    /**
     * 查询用户模型
     *
     */
    public function checkAvter($user_id)
    {
        $modID =  UserAvter::find()->where(['userID' => $user_id])->select(['modID'])->asArray()->scalar();
        if (empty($modID)) {
            return ['code' => -1, 'data' => '不存在信息'];
        }
        return ['code' => 200, 'data' => $modID];
    }
    /**
     * 设置用户模型
     */
    public function setAvter($user_id, $mod_id)
    {
        // 获取信息
        $info =  UserAvter::find()->where(['userID' => $user_id])->asArray()->one();

        $data = [
            'userID' => $user_id,
            'modID' => $mod_id,
        ];
        try {
            $sql = Yii::$app->db->createCommand();
            if (empty($info)) {
                $sql->insert(UserAvter::tableName(), $data);
            } else {
                $sql->update(UserAvter::tableName(), ['modID' => $mod_id], ['userID' => $user_id]);
            }
            $sql->execute();
            return ['code' => 200, 'message' => '操作成功'];
        } catch (Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }
    /**
     * 获取用户信息
     */
    public function getUserInfo($user_id)
    {
        if (!isset($user_id) || empty($user_id)) {
            return ['code' => -1, 'message' => '用户ID不能为空'];
        }
        $userInfo = User::find()->where(['ID' => $user_id])->asArray()->one();
        if (empty($userInfo)) {
            return ['code' => -1, 'message' => '不存在用户信息'];
        }
        $avterInfo = UserAvter::find()->where(['userID' => $user_id])->select(['modID'])->asArray()->one() ?? [];
        $limitInfo = UserLimit::find()->where(['userID' => $user_id])->select(['message', 'card'])->asArray()->one() ?? [];
        $styleInfo = PltfCard::find()->where(['userID' => $user_id])->select(['style'])->asArray()->one() ?? [];

        // $info = array_merge($userInfo, $avterInfo, $limitInfo, $styleInfo);
        $userInfo['modid'] = $avterInfo['modID'] ?? 1;
        $userInfo['message'] = $limitInfo['message'] ?? 1;
        $userInfo['card'] = $limitInfo['card'] ?? 1;
        $userInfo['style'] = $styleInfo['style'] ?? 1;

        return ['code' => 200, 'data' => $userInfo];
    }
    /**
     * 查询该uid绑定的邀请码信息
     *
     */
    public function getIvtcode($user_id)
    {
        $info =  Ivtcode::find()->where(['binging' => $user_id])
            ->select(['roomID', "row", "col", "level", "expire"])
            ->asArray()
            ->one();
        if (empty($info)) {
            return ['code' => -1, 'data' => '未查找到数据'];
        }
        return ['code' => 200, 'data' => $info];
    }


    /**
     * 编辑用户信息
     *
     * @param [type] $data
     * @return void
     */
    public function setUserInfo($data)
    {
        // 获取用户信息
        $userInfo =  User::find()->where(['ID' => $data['user_id']])->asArray()->one();
        $params = [];
        if (isset($data['company']) &&  $userInfo['Company'] != $data['company']) {
            $params['Company'] =  $data['company'];
        }
        if (isset($data['english_company']) &&  $userInfo['EnglishCompany'] != $data['english_company']) {
            $params['EnglishCompany'] =  $data['english_company'];
        }
        if (isset($data['position']) &&  $userInfo['Position'] != $data['position']) {
            $params['Position'] =  $data['position'];
        }
        if (isset($data['english_position']) &&  $userInfo['EnglishPosition'] != $data['english_position']) {
            $params['EnglishPosition'] =  $data['english_position'];
        }
        if (isset($data['email']) &&  $userInfo['email'] != $data['email']) {
            $params['email'] =  $data['email'];
        }
        if (isset($data['phone']) &&  $userInfo['Cellphone'] != $data['phone']) {
            if (Helper::checkPhone($data['phone'])) {
                return ['code' => -1, 'message' => '手机号格式错误'];
            }
            $params['Cellphone'] =  $data['phone'];
        }
        if (empty($params)) {
            return ['code' => -1, 'message' => '请选择修改参数'];
        }
        try {
            Yii::$app->db->createCommand()->update(User::tableName(), $params, ['ID' => $data['user_id']])->execute();
            return ['code' => 200, 'message' => '编辑成功'];
        } catch (Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }

    /**
     * 添加发送名片记录
     *
     * @param [type] $data
     * @return void
     */
    public function setSendCard($data)
    {
        $info = [
            'fromID' => $data['from_id'],
            'toID' => $data['to_id'],
            'type' => $data['type'],
            'name' => $data['name'],
            'company' => $data['company'] ?? NULL,
            'position' => $data['company'] ?? NULL,
            'email' => $data['email'] ?? '-',
            'phone' => $data['phone'] ?? '-',
            'updatetime' => date('Y-m-d H:i:s', time()),
            'ENname'  => $data['eng_name'] ? NULL : $data['eng_name'],
            'ENcompany'  => $data['eng_company'] ? NULL : $data['eng_company'],
            'ENname'  => $data['eng_position'] ? NULL : $data['eng_position'],
        ];
        if (isset($data['phone']) && !empty($data['phone'])) {
            if (Helper::checkPhone($info['phone'])) {
                return ['code' => -1, 'message' => '手机号格式错误'];
            }
        }
        try {
            Yii::$app->db->createCommand()->insert(PltfSendCard::tableName(), $info)->execute();
            return ['code' => 200, 'message' => '添加成功'];
        } catch (Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }
    /**
     * 获取发送名片记录
     *
     * @param [type] $data
     * @return void
     */
    public function getSendCard($data)
    {
        $where = [];
        if (isset($data['to_id']) && !empty($data['to_id'])) {
            $where['toID'] =  $data['to_id'];
        }
        if (isset($data['from_id']) && !empty($data['from_id'])) {
            $where['fromID'] =  $data['from_id'];
        }
        if (empty($where)) {
            return ['code' => -1, 'message' => '缺少参数'];
        }
        $result = PltfSendCard::find()->where($where)->asArray()->all();
        if (empty($result)) {
            return ['code' => -1, 'message' => '暂无数据'];
        }
        return ['code' => 200, 'data' => $result];
    }


    /**
     * 重置邀请码过期会员信息
     *
     */
    public function updateIvtCode()
    {
        // 获取所有已过期或未删除的数据
        $data =  Ivtcode::find()->where(['isDelete' => 0])->andWhere(['<', 'expire', date('Y-m-d H:i:s', time())])->asArray()->all();
        if (!empty($data)) {
            $sql =  Yii::$app->db->createCommand();
            $transaction = Yii::$app->db->beginTransaction();
            try {
                foreach ($data as $key => $item) {
                    if ($item['binging']  >= 1) {
                        $user_id = $item['binging'];
                        //查询用户最新状态
                        $userSeattimelineInfo =  Seattimeline::find()->where(['userID' => $user_id])->orderBy(['updatetime' => SORT_DESC])->asArray()->one();
                        if (!empty($userSeattimelineInfo) && in_array($userSeattimelineInfo['status'], [1, 4, 5])) {
                            if (in_array($userSeattimelineInfo['status'], [1, 5])) {
                                $userSeattimelineInfo['status'] = 2;
                            } elseif ($userSeattimelineInfo['status'] == 4) {
                                $userSeattimelineInfo['status'] = 6;
                            }
                            $userSeattimelineInfo['updatetime'] = date('Y-m-d H:i:s', time());
                            unset($userSeattimelineInfo['ID']); // 销毁ID
                            // 添加踢出状态记录
                            $sql->insert(Seattimeline::tableName(), $userSeattimelineInfo)->execute();
                            $roomInfo =  Room::find()->where(['ID' => $userSeattimelineInfo['roomID']])->asArray()->one();
                            if (!empty($roomInfo) && $roomInfo['curseat'] > 0) {
                                $sql->update(Room::tableName(), ['curseat' => ($roomInfo['curseat'] - 1)], ['ID' => $roomInfo['ID']])->execute();
                            }
                        }
                        // 已绑定用户 ， 重置用户level
                        $sql->update(User::tableName(), ['Level' => 1], ['ID' => $user_id])->execute();
                    }
                    if ($item['row'] > 0 && $item['col'] > 0) {
                        $line = $item['row'];
                        // 存在行列信息，变更seat 表状态
                        $seatInfo = Seat::find()->where(['roomID' => $item['roomID'], 'line' => $line])
                            ->select(['ID', 'seatdate'])
                            ->asArray()->one();
                        if (!empty($seatInfo)) {
                            $seatdate =  explode('/', $seatInfo['seatdate']);
                            $seatdate[$item['col'] - 1] = 0;
                            $new_seatdate = implode('/', $seatdate);
                            // 编辑座位
                            $sql->update(Seat::tableName(), ['seatdate' => $new_seatdate], ['ID' => $seatInfo['ID']])->execute();
                        }
                    }
                    // 编辑验证码状态
                    $sql->update(Ivtcode::tableName(), ['isDelete' => 1, 'binging' => 0], ['ID' => $item['ID']])->execute();
                    if ($key % 100 == 0) { // 每100条提交一次
                        $transaction->commit();
                        $transaction = Yii::$app->db->beginTransaction();
                    }
                }
                $transaction->commit();
            } catch (Exception $e) {
                return ['code' => -1, 'message' => $e->getMessage()];
                $transaction->rollBack();
            }
        }
        return ['code' => 200, 'message' => '操作成功'];
    }
}
